<template>
  <div>
    <input v-model="address" placeholder="请输入地址" />
    <button @click="geocode">获取坐标</button>
    <div v-if="location">
      <p>经度: {{ location.lon }}</p>
      <p>纬度: {{ location.lat }}</p>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      address: "浙江省杭州市滨江区浙新小区", // 输入的地址
      location: null, // 返回的地理坐标
    };
  },
  methods: {
    async geocode() {
      if (!this.address) {
        return;
      }

      const apiKey = "0a19a3562e94920c8d47f559b1ad5ae9"; // 替换为您的天地图开发者密钥
      const url = `https://api.tianditu.gov.cn/geocoder`;

      try {
        const response = await axios.get(url, {
          params: {
            key: apiKey,
            addr: this.address,
          },
        });
        if (response.data.status === "0") {
          this.location = response.data.result.location; // 获取地理坐标
        } else {
          alert("获取地理编码失败: " + response.data.msg);
        }
      } catch (error) {
        console.error("调用地理编码接口出错:", error);
        alert("地理编码请求失败");
      }
    },
  },
};
</script>

<style scoped>
input {
  margin-right: 10px;
}
</style>